package com.gopay.bis.manager.bank.fund;

import com.gopay.bis.dao.fund.FundAccChangeNotifyDAO;
import com.gopay.bis.dao.fund.FundFuploadNotifyDAO;
import com.gopay.bis.dao.fund.FundReconFinishNotifyDAO;
import com.gopay.common.constants.cust.CustCorpInfoConstants;
import com.gopay.common.constants.fund.FundOrderTypeEnum;
import com.gopay.common.constants.fund.FundTranTypeEnum;
import com.gopay.common.constants.holiday.HolidayType;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.cps.dao.fund.FundCpsOrderDao;
import com.gopay.common.cps.dao.fund.FundFileDao;
import com.gopay.common.cps.dao.holiday.HolidayInformationDAO;
import com.gopay.common.cps.dao.order.CpsGeneralFundOrderQueryDAO;
import com.gopay.common.cps.service.fund.BindCardBaseService;
import com.gopay.common.cps.service.fund.FundCpsGenOrder;
import com.gopay.common.domain.cust.CustCorpInfo;
import com.gopay.common.domain.cust.CustInfoExtendItem;
import com.gopay.common.domain.fund.*;
import com.gopay.common.domain.fund.vo.FundType;
import com.gopay.common.domain.fund.vo.PageData;
import com.gopay.common.domain.holiday.HolidayInformation;
import com.gopay.common.exception.GopayException;
import com.gopay.common.user.dao.CustInfoExtendItemDAO;
import com.gopay.common.util.DateUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 中信通知manager实现
 * @CiticNotifyManagerImpl.java
 * @author dong-wang5@hnari.com
 * @2016年6月16日 上午10:26:50  www.gopay.com.cn Inc.All rights reserved.
 */
@Service("citicNotifyManager")
public class CiticNotifyManagerImpl implements CiticNotifyManager{
    private  Logger logger = LoggerFactory.getLogger(CiticNotifyManagerImpl.class);

    private Date today = new Date();
    @Resource(name = "bindCardBaseService")
    private BindCardBaseService cardBaseService;

    @Resource(name = "fundAccChangeNotifyDAO")
    private FundAccChangeNotifyDAO fundAccChangeNotifyDAO;

    @Resource(name = "fundFuploadNotifyDAO")
    private FundFuploadNotifyDAO fundFuploadNotifyDAO;

    @Resource(name = "fundReconFinishNotifyDAO")
    private FundReconFinishNotifyDAO fundReconFinishNotifyDAO;

    @Resource(name = "fundFileDao")
    private FundFileDao fundFileDao;

    @Resource(name = "cpsGeneralFundOrderQueryDAO")
    private CpsGeneralFundOrderQueryDAO cpsGeneralFundOrderQueryDAO;

    @Resource(name ="fundCpsOrderDao")
    private FundCpsOrderDao fundCpsOrderDao;

    @Resource(name = "custInfoExtendItemDAO")
    private CustInfoExtendItemDAO custInfoExtendItemDAO;

    @Resource(name = "fundCpsGenOrder")
    private FundCpsGenOrder fundCpsGenOrder;

    @Resource(name = "holidayInformationDAO")
    private HolidayInformationDAO holidayInformationDAO;



    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public Integer addFileUploadNotify(PageData pageData) {
        /**描述： 文件上传通知去除业务处理  update by:jianghp   2017/11/9 16:49  start*/
        String notifyType = pageData.getString("NOTIFY_TYPE");
        String filePath  = pageData.getString("file_path").replace(" ","");
        logger.info("文件上传通知文件路径："+filePath);
        if(StringUtils.isNotBlank(filePath) && !filePath.contains("supervise-allocation") && !filePath.contains("supervise-transfer")){
            if((StringUtils.isBlank(notifyType) || "RECEIVE".equals(notifyType)) && !"SUPERVISE-TRANSFER".equalsIgnoreCase(pageData.getString("file_type"))){
                //监管行通知国付宝的文件上传通知
                // 同时插入文件表，先根据文件名判断文件是否存在，如果不存在，插入（如果是1文件。文件状态为2，其他类型文件都是成功），如果存在，修改内容。
                //查询文件表中是否存在
                Map fileMap = new HashMap();
                String citicFileName = pageData.getString("file_name").replace(".txt", "");
                logger.info("监管行文件上传通知处理文件开始："+citicFileName);

                //构建文件数据
                FundGopayFileEntity file =  generateFile(null,pageData);
                logger.info("文件上传通知构建文件：" + ToStringBuilder.reflectionToString(file));
                if(file!=null){
                    fileMap.put("fileName", citicFileName);
                    List<FundGopayFileEntity> exists = fundFileDao.queryFileByParam(fileMap);
                    logger.info("监管行文件上传通知在文件表中是否存在：" + exists.size());
                    if(exists.size()==0){
                        //新增文件
                        fundFileDao.save(file);
                    }else if(exists.size()==1){
                        //  add by baiyunpeng   防止赎回重复通知导致订单重复
                        if(FundType.SUPERVISE_REDEEM.value.equals(pageData.getString("file_type").replace(" ",""))){
                            if (exists.get(0).getFileStatus() != null && "1".equals(exists.get(0).getFileStatus().toString())) {
                                logger.error("监管行给国付宝的赎回文件通知  重复通知  会造成订单重复生成...............故不保存..............");
                                return -1;
                            }
                        }
                        //修改文件数据
                        FundGopayFileEntity queryOrder = exists.get(0);
                        if(StringUtils.isNotBlank(file.getFileName())){
                            queryOrder.setFileName(file.getFileName());
                        }
                        if(StringUtils.isNotBlank(file.getFileType())){
                            queryOrder.setFileType(file.getFileType());
                        }
                        if(StringUtils.isNotBlank(file.getFilePath())){
                            queryOrder.setFilePath(file.getFilePath());
                        }
                        if(StringUtils.isNotBlank(file.getFileStatus())){
                            queryOrder.setFileStatus(file.getFileStatus());
                        }
                        if(file.getSettleTime()!= null){
                            queryOrder.setSettleTime(file.getSettleTime());
                        }
                        if(file.getReconciliationTime()!= null){
                            queryOrder.setReconciliationTime(file.getReconciliationTime());
                        }
                        if(StringUtils.isNotBlank(file.getMemo())){
                            queryOrder.setMemo(file.getMemo());
                        }
                        if(StringUtils.isNotBlank(file.getIsNotify())){
                            queryOrder.setIsNotify(file.getIsNotify());
                        }
                        if(StringUtils.isNotBlank(file.getCustId())){
                            queryOrder.setCustId(file.getCustId());
                        }
                        queryOrder.setLastUpdTs(new Date());
                        fundFileDao.update(queryOrder);
                    }else{
                        return -1;
                    }
                }else{
                    return -1;
                }
            }else{
                logger.info("不通过文件上传通知处理文件："+pageData.getString("file_name"));
            }
        }else{
            logger.info("申购认购文件业务不通过文件上传通知处理文件："+pageData.getString("file_name"));
        }
        /**描述： 文件上传通知去除业务处理  update by:jianghp   2017/11/9 16:49  end*/
        FundGopayFuploadNotifyEntity fuploadNotifyEntity = bulidFileUploadNotify(pageData);
        fundFuploadNotifyDAO.save(fuploadNotifyEntity);
        return 0;
    }

    /**
     * 构建文件数据
     */
    @Deprecated
    private FundGopayFileEntity generateFile(FundGopayFileEntity fundGopayFileEntity,PageData pageData) {
        if(fundGopayFileEntity == null ){
            fundGopayFileEntity = new FundGopayFileEntity();
        }
        try {
            /***baiyunpeng    添加去空格  .replace(" ","") ***/
            fundGopayFileEntity.setFileName(pageData.getString("file_name").replace(".txt","").replace(" ",""));
            fundGopayFileEntity.setFileType(pageData.getString("file_type").replace(" ",""));
            fundGopayFileEntity.setFilePath(pageData.getString("file_path").replace(" ",""));
            if (FundType.SUPERVISE_DIFFERENCE.value.equals(fundGopayFileEntity.getFileType())){
                logger.info("差异文件开始睡眠两秒，等待对账完成通知处理");
                Thread.sleep(2000);
            }
            //获取对账文件
            String differenceFileNameAll = pageData.getString("file_name").replace(".txt", "").replace(" ","");
            String fileNameAll = differenceFileNameAll.replace("_difference","");//文件名称
            String pathF = pageData.getString("file_path");
            if(StringUtils.isNotEmpty(pathF) && pathF.indexOf("supervise-allocation/")>-1){
                //说明是调拨文件
                fileNameAll = differenceFileNameAll.replace("_difference", "_allocation");
            }
            logger.info("根据差异文件获取对账文件名称："+fileNameAll);
            Map fileMap = new HashMap();
            fileMap.put("fileName","%"+fileNameAll+"%");
            List<FundGopayFileEntity> fileExists = fundFileDao.queryFileByParam(fileMap);

            if(FundType.SUPERVISE_REDEEM.value.equals(pageData.getString("file_type").replace(" ",""))){
                //如果是分红退款文件
                fundGopayFileEntity.setFileStatus("2");//处理中
                fundGopayFileEntity.setReconciliationStatus("0");//未对账
                fundGopayFileEntity.setSettleStatus("0");//未结算
                // 赎回分红落地需要 : baiyunpeng
                String fileName = fundGopayFileEntity.getFileName();
                int i1 = fileName.indexOf("_");
                String fundNo = fileName.substring(0, i1);
                CustInfoExtendItem ciei_fundNo = custInfoExtendItemDAO.findCustInfoExtendItemByItemKey(CustCorpInfoConstants.ITEM_KEY_FUNDORGNO, fundNo);
                fundGopayFileEntity.setCustId(ciei_fundNo.getCustId());
            }else{
                //之前的setCustId挪到这里  :  只要不是赎回都设置成0  2016/07/13 baiyunpeng
                if(fileExists.size()==1){
                    fundGopayFileEntity.setCustId(fileExists.get(0).getCustId());//商户Id
                }else{
                	logger.error("调拨文件不存在，数据异常，请检查！！ " + fileExists.size());
                    fundGopayFileEntity.setCustId("0");//商户ID   0 代表监管行通知我们的文件
                }
            }

            fundGopayFileEntity.setMemo(pageData.getString("memo"));
            fundGopayFileEntity.setSource("p");
            fundGopayFileEntity.setCreatedTs(new Date());
            fundGopayFileEntity.setLastUpdTs(new Date());
            fundGopayFileEntity.setIsNotify("1");//默认监管行已经通知国付宝

            //清算日期
            if(fileExists.size()==1){
                fundGopayFileEntity.setSettleTime(fileExists.get(0).getSettleTime());//清算时间
            }else{
                fundGopayFileEntity.setSettleTime(new Date());//清算时间 ????
            }
            fundGopayFileEntity.setReconciliationTime(new Date());//对账时间 ????


        } catch (Exception e) {
            e.printStackTrace();
            logger.error("监管行文件通知读取文件失败！");
            return null;
        }

        return fundGopayFileEntity;
    }

    /**
     * 构建文件上传通知数据
     * by Jason
     *
     */
    private FundGopayFuploadNotifyEntity bulidFileUploadNotify(PageData pageData) {
        FundGopayFuploadNotifyEntity fuploadNotifyEntity = new FundGopayFuploadNotifyEntity();
        String notifyType = pageData.getString("NOTIFY_TYPE");
        if(StringUtils.isNotBlank(notifyType) && "SEND".equals(notifyType)){
            fuploadNotifyEntity.setNotifyType("SEND");
        }else{
            fuploadNotifyEntity.setNotifyType("RECEIVE");
        }

        fuploadNotifyEntity.setSerialNo(pageData.getString("serial_no"));
        fuploadNotifyEntity.setFileName(pageData.getString("file_name"));
        fuploadNotifyEntity.setFileType(pageData.getString("file_type"));
        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
        String file_upload_time = pageData.getString("file_upload_time");
        try {
            fuploadNotifyEntity.setFileUploadTime(sdf.parse(file_upload_time));
        } catch (ParseException e) {
            e.printStackTrace();
            fuploadNotifyEntity.setFileUploadTime(new Timestamp(DateUtils.getSystemDate().getTime()));
        }
        fuploadNotifyEntity.setFilePath(pageData.getString("file_path"));
        fuploadNotifyEntity.setMemo(pageData.getString("memo"));
        fuploadNotifyEntity.setIsSucc("Y");
        fuploadNotifyEntity.setDepositTime(new Timestamp(DateUtils.getSystemDate().getTime()));
        fuploadNotifyEntity.setErrorCode(pageData.getString("error_code"));
        fuploadNotifyEntity.setErrorMsg(pageData.getString("error_msg"));
        fuploadNotifyEntity.setSource("P");
        fuploadNotifyEntity.setCreatedTs(new Timestamp(DateUtils.getSystemDate().getTime()));
        fuploadNotifyEntity.setLastUpdTs(new Timestamp(DateUtils.getSystemDate().getTime()));
        fuploadNotifyEntity.setReturnUrl(pageData.getString("return_url"));
        return fuploadNotifyEntity;
    }

    @Override
    public Integer addAccountChangeNotify(PageData pageData) {
        FundGoapayAccChangeNotify accChangeNotify = new FundGoapayAccChangeNotify();
        accChangeNotify.setSerialNo(pageData.getString("serial_no"));
        accChangeNotify.setAccountStatus(pageData.getString("account_status"));
        accChangeNotify.setBalance(Double.valueOf(pageData.getString("balance")));
        accChangeNotify.setMsgType(pageData.getString("msg_type"));
        accChangeNotify.setAccount(pageData.getString("account"));
        accChangeNotify.setAccountName(pageData.getString("account_name"));
        accChangeNotify.setFileBatchNo(pageData.getString("file_batch_no"));
        SimpleDateFormat sdf=new SimpleDateFormat("yyMMddHHmmss");
        String bank_notify_time = pageData.getString("bank_notify_time");
        try {
            accChangeNotify.setBankNotifyTime(sdf.parse(bank_notify_time));
        } catch (ParseException e) {
            e.printStackTrace();
            accChangeNotify.setBankNotifyTime(new Timestamp(DateUtils.getSystemDate().getTime()));
        }
        accChangeNotify.setMemo(pageData.getString("memo"));
        accChangeNotify.setIsSucc("Y");
        accChangeNotify.setDepositTime(new Timestamp(DateUtils.getSystemDate().getTime()));
        accChangeNotify.setErrorCode(pageData.getString("error_code"));
        accChangeNotify.setErrorMsg(pageData.getString("error_msg"));
        accChangeNotify.setSource("P");
        accChangeNotify.setCreatedTs(new Timestamp(DateUtils.getSystemDate().getTime()));
        accChangeNotify.setLastUpdTs(new Timestamp(DateUtils.getSystemDate().getTime()));
        accChangeNotify.setReturnUrl(pageData.getString("return_url"));
        logger.info("账户变动通知参数："+ ToStringBuilder.reflectionToString(accChangeNotify));
        fundAccChangeNotifyDAO.save(accChangeNotify);
        return 0;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public Integer addReconFinishNotify(PageData pageData) {
        //构建对账完成通知记录
        FundGopayReconFinishNotifyEntity reconFinishNotify = bulidReconFinishNotify(pageData);
        logger.info("对账完成通知参数："+ ToStringBuilder.reflectionToString(reconFinishNotify));
        fundReconFinishNotifyDAO.save(reconFinishNotify);
       /**描述： 对账完成通知去除业务处理  update by:jianghp   2017/11/9 16:49  start*/
        /*//差异文件处理
        saveOrUpdateFile(pageData);
        //根据对账完成通知去更新文件和订单的状态
        doFileAndOrder(pageData);*/
       /**描述：对账完成通知去除业务处理   update by:jianghp   2017/11/9 16:49  end*/
        String filePath  = pageData.getString("file_path").replace(" ","");
        logger.info("对账完成通知文件路径："+filePath);
        if(StringUtils.isNotBlank(filePath) && !filePath.contains("supervise-allocation") && !filePath.contains("supervise-transfer")){
            //差异文件处理
            saveOrUpdateFile(pageData);
        }else{
            logger.info("申购认购业务不做对账完成通知操作！");
        }
        return 0;
    }

    @Deprecated
    private void saveOrUpdateFile(PageData pageData) {
        Map fileMap = new HashMap();
        String citicFileName = pageData.getString("difference_file_name").replace(".txt", "");
        fileMap.put("fileName", citicFileName);
        List<FundGopayFileEntity> exists = fundFileDao.queryFileByParam(fileMap);
        logger.info("差异文件在文件表中是否存在：" + exists.size());
        if(exists.size()==0){
            FundGopayFileEntity file = new FundGopayFileEntity();
            file.setFileName(pageData.getString("difference_file_name").replace(".txt", ""));
            file.setFilePath(pageData.getString("file_path"));
            file.setCreatedTs(new Date());
            file.setLastUpdTs(new Date());
            file.setSettleTime(new Date());//默认当天
            file.setReconciliationTime(new Date());
            file.setSource("p");
            file.setCustId("0");//默认监管行
            file.setIsNotify("0");//默认未通知
            String totalAmount = pageData.getString("difference_total");
            String totalSum = pageData.getString("difference_num");
            if(StringUtils.isNotEmpty(totalAmount) && StringUtils.isNotEmpty(totalSum)){
                file.setFileStatus("1");//成功
                if("0".equals(totalSum)){
                    file.setReconciliationStatus("2");//对账成功
                    file.setSettleStatus("1");//已结算
                }else{
                    file.setReconciliationStatus("1");//对账失败
                    file.setSettleStatus("0");//未结算
                }
                file.setTotalAmount(new BigDecimal(totalAmount));
                file.setTotalSum(new Integer(totalSum));
            }
            //新增文件
            fundFileDao.save(file);
        }else if(exists.size()==1){
            FundGopayFileEntity file = exists.get(0);
            file.setLastUpdTs(new Date());
            String totalAmount = pageData.getString("difference_total");
            String totalSum = pageData.getString("difference_num");
            if(StringUtils.isNotEmpty(totalAmount) && StringUtils.isNotEmpty(totalSum)){
                file.setFileStatus("1");//成功
                if("0".equals(totalSum)){
                    file.setReconciliationStatus("2");//对账成功
                    file.setSettleStatus("1");//已结算
                }else{
                    file.setReconciliationStatus("1");//对账失败
                    file.setSettleStatus("0");//未结算
                }
                file.setTotalAmount(new BigDecimal(totalAmount));
                file.setTotalSum(new Integer(totalSum));
            }
            fundFileDao.update(file);
        }
    }

    /**
     * 根据对账完成通知去更新文件和订单的状态
     * @param pageData
     */
    @Deprecated
    private void doFileAndOrder(PageData pageData) {
        logger.info("根据对账完成通知去更新文件和订单的状态开始！！！！！！");
        String differenceFileName = pageData.getString("difference_file_name").replace(".txt", "");
        logger.info("根据对账完成通知差异文件名称："+differenceFileName);
        String status = pageData.getString("status");
        int differenceNum = Integer.parseInt(pageData.getString("difference_num"));

        String fileName = differenceFileName.replace("_difference","");//文件名称
        String filePath = pageData.getString("file_path");
        if(StringUtils.isNotEmpty(filePath) && filePath.startsWith("supervise-allocation/")){
            //说明是调拨文件
            fileName = differenceFileName.replace("_difference", "_allocation");
        }
        logger.info("根据对账完成通知文件名称："+fileName);

        Map fileMap = new HashMap();
        fileMap.put("fileName","%"+fileName+"%");
        List<FundGopayFileEntity> fileExists = fundFileDao.queryFileByParam(fileMap);
        if(fileExists.size()==1){
            //文件存在
            FundGopayFileEntity file = fileExists.get(0);
            if(FundType.ALLOCATION.value.equals(file.getFileType())){ //调拨文件的差异文件
                if("1".equalsIgnoreCase(file.getFileStatus()) && differenceNum==0 && "Y".equals(status)){
                    doDifference0File(file,fileName,true);
                }else{
                    doDifference0File(file,fileName,false);
                }

            }else if(FundType.TRANSFER_GF.value.equals(file.getFileType())){//理财转基金文件 的差异文件
                if("1".equalsIgnoreCase(file.getFileStatus()) && differenceNum==0 && "Y".equals(status)){
                    //只更新文件
                    file.setReconciliationStatus("2");//对账成功
                    file.setReconciliationTime(new Date());
                    file.setSettleStatus("1");//已结算
                    fundFileDao.update(file);
                }else{
                    //只更新文件
                    file.setReconciliationStatus("1");//对账失败
                    file.setReconciliationTime(new Date());
                    file.setSettleStatus("1");//已结算
                    fundFileDao.update(file);
                }
            }

        } else{
            logger.info("根据对账完成通知无法找到该文件！");
        }

    }

    /**
     * 调拨文件的差异文件 后续处理
     */
    @Deprecated
    private void doDifference0File(FundGopayFileEntity file,String fileName,boolean flag) {
        logger.info("调拨文件的差异文件 后续处理！");
        if(flag){
            file.setReconciliationStatus("2");//对账成功
        }else{
            file.setReconciliationStatus("1");//对账失败
        }
        file.setReconciliationTime(new Date());
        file.setSettleStatus("1");//已结算
        file.setLastUpdTs(new Date());
        fundFileDao.update(file);

        //更新基金支付订单为交易成功，主订单为成功
        String[] tranType = new String[]{FundTranTypeEnum.SUBSCRIPTION.value,FundTranTypeEnum.REQUISITION.value};
        String fileDay = fileName.split("_")[fileName.split("_").length-1];
        Calendar calendar = Calendar.getInstance();  //得到日历
        Date dNow = DateUtils.strToDate(fileDay,"yyyyMMdd");
        try {
            calendar.setTime(getTaddN(dNow,1,HolidayType.FUND_COMPANY));
            String settleDay = DateUtils.formatDate(calendar.getTime(), "yyyyMMdd");
            Map paraMap = new HashMap();
            paraMap.put("tranType",tranType);

            paraMap.put("stlmDate",settleDay);
            logger.info(">>>>>>>>>>>>>>>>>>>>33333333333333");
            String fundNo = fileName.split("_")[0];
            CustInfoExtendItem ciei_fundNo = custInfoExtendItemDAO.findCustInfoExtendItemByItemKey(CustCorpInfoConstants.ITEM_KEY_FUNDORGNO, fundNo);
            if(ciei_fundNo!=null){
                paraMap.put("merchantId",ciei_fundNo.getCustId());
            }
            List<FundGopayCpsGenOrder> fundOrders = new ArrayList<>();
            String orderType = FundOrderTypeEnum.RECONCILIATION.getValue();//对账中
            paraMap.put("orderType",orderType);
            List<FundGopayCpsGenOrder> fundOrders01 = queryOrderOfFund(paraMap);//对账中的订单
            fundOrders.addAll(fundOrders01);
            orderType = FundOrderTypeEnum.RECONCILIATION_FAIL.getValue();//对账失败
            paraMap.put("orderType",orderType);
            List<FundGopayCpsGenOrder> fundOrders02 = queryOrderOfFund(paraMap);//对账失败的订单
            fundOrders.addAll(fundOrders02);
            List<String> keyIds = new ArrayList<>();
            List<String> gopayIds = new ArrayList<>();

            if(fundOrders!=null){
                for (int i = 0; i <fundOrders.size() ; i++) {
                    keyIds.add(fundOrders.get(i).getKeyId());
                    gopayIds.add(fundOrders.get(i).getGopayOrderId());
                }
            }

            Map<String, Object> fundoderMaps = new HashMap<>();
            Map<String, Object> mainOderMaps = new HashMap<>();

            fundoderMaps.put("keyIds", keyIds);
            fundoderMaps.put("lastUpdTs", new Date());
            String lastOrderType = FundOrderTypeEnum.RECONCILIATION_SUCC.value;//对账成功
            if(!flag){
            	lastOrderType = FundOrderTypeEnum.RECONCILIATION.value;//对账中
            }
            fundoderMaps.put("orderType", lastOrderType);
            mainOderMaps.put("keyIds", gopayIds);
            mainOderMaps.put("txnStaCd", 20000);//处理中
            mainOderMaps.put("lastUpdTs", new Date());
            if(keyIds.size()>0) fundCpsOrderDao.updateFundMainOrder(fundoderMaps);
            if(gopayIds.size()>0) fundCpsOrderDao.updateMainOrder(mainOderMaps);

        } catch (GopayException e) {
            e.printStackTrace();
            logger.error("获取结算时间错误：" + e.getMessage());
        }

    }

    /**
     * 获取清算日期
     */
    @Deprecated
    public Date getTaddN(Date t, int n, HolidayType holidayType) throws GopayException {
        logger.error("HolidayService 计算t+n:" + t + ", " + n + ", " + holidayType);
        if (n<0) {
            logger.error("n < 0");
            return null;
        }
        Calendar c = Calendar.getInstance();
        c.setTime(t);
        Set<String> holidaySet = getMonthHoliday(holidayType, String.valueOf(c.get(Calendar.YEAR)),
                String.valueOf(c.get(Calendar.MONTH) + 1));
        // 当天是节假日,则起始日期向后推1天，直到非节假日为止
        while (holidaySet.contains(String.valueOf(c.get(Calendar.DAY_OF_MONTH)))) {
            c.add(Calendar.DAY_OF_MONTH, 1);
            // 如果加了1天后，为当月第一天，即月份变化后，需要重新读取节假日配置
            if (c.get(Calendar.DAY_OF_MONTH) == 1) {
                holidaySet = getMonthHoliday(holidayType, String.valueOf(c.get(Calendar.YEAR)),
                        String.valueOf(c.get(Calendar.MONTH) + 1));
            }
        }
        //开始计算n天后日期，期间略过休息日
        for (int i = 0; i < n; i++) {
            c.add(Calendar.DAY_OF_MONTH, 1);
            // 如果加了1天后，为当月第一天，即月份变化后，需要重新读取节假日配置
            if (c.get(Calendar.DAY_OF_MONTH) == 1) {
                holidaySet = getMonthHoliday(holidayType, String.valueOf(c.get(Calendar.YEAR)),
                        String.valueOf(c.get(Calendar.MONTH) + 1));
            }
            if (holidaySet.contains(String.valueOf(c.get(Calendar.DAY_OF_MONTH)))) {
                n++;
            }
        }
        logger.error("HolidayService 计算节假日结果:" + c.getTime());
        return c.getTime();
    }

    @Deprecated
    private Set<String> getMonthHoliday(HolidayType holidayType, String year, String month) throws GopayException {
        HolidayInformation h = holidayInformationDAO.getHolidayInformationByYearandMonth(holidayType, year, month);
        if (h != null) {
            String holidays = h.getHolidays();
            if (StringUtils.isNotBlank(holidays)) {
                String[] holidays_array = holidays.split(",");
                Set<String> holidaySet = new HashSet<String>();
                for (String holiday : holidays_array) {
                    holidaySet.add(holiday);
                }
                return holidaySet;
            }
        } else {
            logger.error("未查到节假日信息");
            // 查询不到数据时抛出异常
            throw new GopayException(ProcCodeConstants.PROC_CODE_100E6001);
        }
        return null;
    }

    /**
     * 构建对账完成通知记录
     * @param pageData
     * @return
     */
    private FundGopayReconFinishNotifyEntity bulidReconFinishNotify(PageData pageData) {
        FundGopayReconFinishNotifyEntity reconFinishNotify = new FundGopayReconFinishNotifyEntity();
        reconFinishNotify.setSerialNo(pageData.getString("serial_no"));
        reconFinishNotify.setStatus(pageData.getString("status"));
        reconFinishNotify.setDifferenceNum(Integer.parseInt(pageData.getString("difference_num")));
        reconFinishNotify.setDifferenceTotal(Double.parseDouble(pageData.getString("difference_total")));
        reconFinishNotify.setDifferenceFileName(pageData.getString("difference_file_name"));
        reconFinishNotify.setFilePath(pageData.getString("file_path"));
        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
        SimpleDateFormat format=new SimpleDateFormat("yyyyMMdd");
        String reconciliation_finish_time = pageData.getString("reconciliation_finish_time");
        String reconciliation_date = pageData.getString("reconciliation_date");
        try {
            reconFinishNotify.setReconciliationFinishTime(sdf.parse(reconciliation_finish_time));
        } catch (ParseException e) {
            e.printStackTrace();
            reconFinishNotify.setReconciliationFinishTime(new Timestamp(DateUtils.getSystemDate().getTime()));
        }
        try {
            reconFinishNotify.setReconciliationDate(format.parse(reconciliation_date));
        } catch (ParseException e) {
            e.printStackTrace();
            reconFinishNotify.setReconciliationDate(new Timestamp(DateUtils.getSystemDate().getTime()));
        }
        reconFinishNotify.setMemo(pageData.getString("memo"));
        reconFinishNotify.setIsSucc("Y");
        reconFinishNotify.setDepositTime(new Timestamp(DateUtils.getSystemDate().getTime()));
        reconFinishNotify.setErrorCode(pageData.getString("error_code"));
        reconFinishNotify.setErrorMsg(pageData.getString("error_msg"));
        reconFinishNotify.setSource("P");
        reconFinishNotify.setCreatedTs(new Timestamp(DateUtils.getSystemDate().getTime()));
        reconFinishNotify.setLastUpdTs(new Timestamp(DateUtils.getSystemDate().getTime()));
        reconFinishNotify.setReturnUrl(pageData.getString("return_url"));
        return reconFinishNotify;
    }

    /**
     * 查询基金支付订单
     * @param paraMap
     * @return
     */
    @Deprecated
    private List<FundGopayCpsGenOrder> queryOrderOfFund(Map paraMap) {
        List<FundGopayCpsGenOrder> orderList=new ArrayList<FundGopayCpsGenOrder>();
        StringBuilder sb = new StringBuilder();
        sb.append(" from FundGopayCpsGenOrder t where 1=1 ");

        if(paraMap!=null){
            if(paraMap.get("merchantId")!=null){
                sb.append(" and t.merchantId = :merchantId");
            }
            if(paraMap.get("orderType")!=null){
                sb.append(" and t.orderType = :orderType");
            }
            if(paraMap.get("tranType")!=null){
                sb.append(" and t.tranType in (:tranType)");
            }
            if(paraMap.get("stlmDate")!=null){
                sb.append(" and to_char(t.stlmDate,'yyyyMMdd') = :stlmDate and t.merTxnTm >= sysdate-60");
            }
            if(paraMap.get("dateBegin")!=null){
                sb.append(" and t.merTxnTm >= to_timestamp(:dateBegin, 'yyyymmddHH24miss')");
            }
            if(paraMap.get("dateEnd")!=null){
                sb.append(" and t.merTxnTm < to_timestamp(:dateEnd, 'yyyymmddHH24miss')");
            }
        }

        orderList = cpsGeneralFundOrderQueryDAO.findByHql(sb.toString(),paraMap);
        return orderList;
    }

    /**
     * 条件查询文件上传通知
     * @param pageData
     * @return
     */
    @Override
    public List<FundGopayFuploadNotifyEntity> queryFileUploadNotify(PageData pageData) {
        String serialNo = pageData.getString("serial_no");
        String file_name = "%"+pageData.getString("file_name")+"%";
        String hql = "from FundGopayFuploadNotifyEntity t where t.serialNo = :serialNo and t.fileName like :fileName";
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("serialNo",serialNo);
        param.put("fileName",file_name);
        return fundFuploadNotifyDAO.findByHql(hql,param);
    }

    /**
     * 条件查询账户变动通知
     * @param pageData
     * @return
     */
    @Override
    public List<FundGoapayAccChangeNotify> queryAccChangeNotify(PageData pageData) {
        String serialNo = pageData.getString("serial_no");
        String file_batch_no = pageData.getString("file_batch_no");
        String hql = "from FundGoapayAccChangeNotify t where t.serialNo = :serialNo and t.fileBatchNo = :fileBatchNo";
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("serialNo",serialNo);
        param.put("fileBatchNo",file_batch_no);
        return fundAccChangeNotifyDAO.findByHql(hql,param);
    }

    /**
     * 条件查询对账完成通知
     * @param pageData
     * @return
     */
    @Override
    public List<FundGopayReconFinishNotifyEntity> queryReconFinishNotify(PageData pageData) {
        String serialNo = pageData.getString("serial_no");
        String hql = "from FundGopayReconFinishNotifyEntity t where t.serialNo = :serialNo";
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("serialNo",serialNo);
        return fundReconFinishNotifyDAO.findByHql(hql,param);
    }

    /**
     * 获得所有基金公司商户的ID
     * @return
     */
    @Deprecated
    private List<String> queryAllFundCorpIds() {
        List<String> merchantIds = new ArrayList<>();
        List<CustCorpInfo> custCorpInfos = fundCpsGenOrder.queryAllFundCorp(null);
        for(CustCorpInfo corp:custCorpInfos){
            merchantIds.add(corp.getCustId());
        }
        return merchantIds;

    }
}
